//
//  ImagesWithOutContentTableViewCell.m
//  YellowBridge
//
//  Created by 王右 on 2018/12/3.
//  Copyright © 2018 王右. All rights reserved.
//

#import "ImagesWithOutContentTableViewCell.h"
#import "ImageCollectionViewCell.h"

@interface ImagesWithOutContentTableViewCell ()<QMUITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) UICollectionView *imagesCollectionView;

@property (strong, nonatomic)  QMUITextView *contentTextView;

@property (nonatomic, assign) CGFloat cellHeight;

@property (strong, nonatomic) IBOutlet UIView *categaoryChangeContainerView;

@property (strong, nonatomic) IBOutlet UILabel *sliderLabel;

@property (nonatomic, strong) UIButton *lastSelectButton;

@property (strong, nonatomic) IBOutlet UIButton *fagaiButton;

@property (nonatomic, strong) NSString *textViewText;

@end



@implementation ImagesWithOutContentTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    _guihuaImageArr = [NSMutableArray array];
    _fagaiImageArr = [NSMutableArray array];
    _guotuImageArr = [NSMutableArray array];
    _zhujianImageArr = [NSMutableArray array];
    _huanbaoImageArr = [NSMutableArray array];

//    _type = BaoJianShouXuCellTypeFaGai;
    _lastSelectButton = _fagaiButton;
    _cellHeight = 215;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置CollectionView的属性
    self.imagesCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(12, _categaoryChangeContainerView.frame.origin.y + _categaoryChangeContainerView.bounds.size.height+5, SCREEN_WIDTH - 12, 80) collectionViewLayout:flowLayout];
    self.imagesCollectionView.backgroundColor = [UIColor whiteColor];
    self.imagesCollectionView.delegate = self;
    self.imagesCollectionView.dataSource = self;
    self.imagesCollectionView.scrollEnabled = YES;
    [self addSubview:self.imagesCollectionView];
    //注册Cell
    [self.imagesCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ImageCollectionViewCell class]) bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ImageCollectionViewCell"];
    
    self.imagesCollectionView.showsHorizontalScrollIndicator = NO;
    
    _contentTextView = [[QMUITextView alloc] init];
    [self addSubview:_contentTextView];
    [_contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_nameLabel);
        make.bottom.right.equalTo(self).with.offset(-15);
        make.top.equalTo(self->_imagesCollectionView.mas_bottom).with.offset(5);
    }];
    _contentTextView.delegate = self;
    _contentTextView.placeholder = @"请输入文字说明";
    _contentTextView.font = [UIFont systemFontOfSize:15];
}

- (IBAction)categoryChangeButtonAction:(UIButton *)sender {
    
    NSInteger tag  = sender.tag;
    self.type = tag % 88880;

    if (tag == _lastSelectButton.tag) {
        return;
    }else{
        _lastSelectButton.selected = NO;
        sender.selected = YES;
        _lastSelectButton = sender;
        [self animatedWithButton:sender];
    }
    [_imagesCollectionView reloadData];
}

- (void)animatedWithButton:(UIButton *)button{
    [UIView animateWithDuration:0.3 animations:^{
        self->_sliderLabel.frame = CGRectMake(button.frame.origin.x, self->_sliderLabel.frame.origin.y, CGRectGetWidth(self->_sliderLabel.bounds), CGRectGetHeight(self->_sliderLabel.bounds));
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    switch (_type) {
        case BaoJianShouXuCellTypeFaGai:
            return  !_canEdit ? _fagaiImageArr.count : (_fagaiImageArr.count+1>9?9:_fagaiImageArr.count+1);
            break;
        case BaoJianShouXuCellTypeGuoTu:
            return  !_canEdit ? _guotuImageArr.count : (_guotuImageArr.count+1>9?9:_guotuImageArr.count+1);
            break;
        case BaoJianShouXuCellTypeGuiHua:
            return  !_canEdit ? _guihuaImageArr.count : (_guihuaImageArr.count+1>9?9:_guihuaImageArr.count+1);
            break;
        case BaoJianShouXuCellTypeHuanBao:
            return  !_canEdit ? _huanbaoImageArr.count : (_huanbaoImageArr.count+1>9?9:_huanbaoImageArr.count+1);
            break;
        case BaoJianShouXuCellTypeZhuJian:
            return  !_canEdit ? _zhujianImageArr.count : (_zhujianImageArr.count+1>9?9:_zhujianImageArr.count+1);
            break;
        default:
            return 0;
            break;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
    [cell.deleteButton setActionWithBlock:^(UIControl *control) {
        [self deleteImageAtType:self->_type atIndex:indexPath.row];
    }];
    NSString *imageUrl;
    if (_canEdit) {
        cell.type = ImageCellTypeCanDelete;
    }else{
        cell.type = ImageCellTypeNormal;
    }
    switch (_type) {
        case BaoJianShouXuCellTypeFaGai:
            if (indexPath.row == _fagaiImageArr.count) {
                cell.imageView.image = [UIImage imageNamed:@"加图片"];
                cell.type = ImageCellTypeNormal;
            }else{
                imageUrl = _fagaiImageArr[indexPath.row];
            }
            break;
        case BaoJianShouXuCellTypeGuoTu:
            if (indexPath.row == _guotuImageArr.count) {
                cell.type = ImageCellTypeNormal;
                cell.imageView.image = [UIImage imageNamed:@"加图片"];
            }else{
                imageUrl = _guotuImageArr[indexPath.row];
            }
            break;
        case BaoJianShouXuCellTypeGuiHua:
            if (indexPath.row == _guihuaImageArr.count) {
                cell.type = ImageCellTypeNormal;
                cell.imageView.image = [UIImage imageNamed:@"加图片"];
            }else{
                imageUrl = _guihuaImageArr[indexPath.row];
            }
            break;
        case BaoJianShouXuCellTypeHuanBao:
            if (indexPath.row == _huanbaoImageArr.count) {
                cell.type = ImageCellTypeNormal;
                cell.imageView.image = [UIImage imageNamed:@"加图片"];
            }else{
                imageUrl = _huanbaoImageArr[indexPath.row];
            }
            break;
        case BaoJianShouXuCellTypeZhuJian:
            if (indexPath.row == _zhujianImageArr.count) {
                cell.type = ImageCellTypeNormal;
                cell.imageView.image = [UIImage imageNamed:@"加图片"];
            }else{
                imageUrl = _zhujianImageArr[indexPath.row];
            }
            break;
        default:
            return 0;
            break;
    }
    if (imageUrl.length != 0) {
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    }
    return cell;
}

- (void)deleteImageAtType:(BaoJianShouXuCellType )type atIndex:(NSInteger )index{
    switch (type) {
        case BaoJianShouXuCellTypeFaGai:
            [_fagaiImageArr removeObjectAtIndex:index];
            break;
        case BaoJianShouXuCellTypeGuoTu:
            [_guotuImageArr removeObjectAtIndex:index];
            break;
        case BaoJianShouXuCellTypeGuiHua:
            [_guihuaImageArr removeObjectAtIndex:index];
            break;
        case BaoJianShouXuCellTypeHuanBao:
            [_huanbaoImageArr removeObjectAtIndex:index];
            break;
        case BaoJianShouXuCellTypeZhuJian:
            [_zhujianImageArr removeObjectAtIndex:index];
            break;
    }
    [_imagesCollectionView reloadData];
}

#pragma mark  定义每个UICollectionView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return  CGSizeMake(80,80);
}

#pragma mark  点击CollectionView触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *imageArr;
    switch (_type) {
        case BaoJianShouXuCellTypeFaGai:
            if (_canEdit) {
                if (indexPath.item == _fagaiImageArr.count) {
                    __weak typeof(self) weakSelf = self;
                    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"选择照片" buttonTitles:@[@"拍照",@"从手机相册选择"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
                        if (index == 0) {
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
                        }else  if (index == 1){
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
                        }
                    }];
                    [sheet show];
                }
            }else{
                imageArr = _fagaiImageArr;
            }
            break;
        case BaoJianShouXuCellTypeGuoTu:
            if (_canEdit) {
                if (indexPath.item == _guotuImageArr.count) {
                    __weak typeof(self) weakSelf = self;
                    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"选择照片" buttonTitles:@[@"拍照",@"从手机相册选择"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
                        if (index == 0) {
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
                        }else  if (index == 1){
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
                        }
                    }];
                    [sheet show];
                }
            }else{
                imageArr = _guotuImageArr;
            }
            break;
        case BaoJianShouXuCellTypeGuiHua:
            if (_canEdit) {
                if (indexPath.item == _guihuaImageArr.count) {
                    __weak typeof(self) weakSelf = self;
                    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"选择照片" buttonTitles:@[@"拍照",@"从手机相册选择"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
                        if (index == 0) {
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
                        }else  if (index == 1){
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
                        }
                    }];
                    [sheet show];
                }
            }else{
                imageArr = _guihuaImageArr;
            }
            break;
        case BaoJianShouXuCellTypeHuanBao:
            if (_canEdit) {
                if (indexPath.item == _huanbaoImageArr.count) {
                    __weak typeof(self) weakSelf = self;
                    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"选择照片" buttonTitles:@[@"拍照",@"从手机相册选择"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
                        if (index == 0) {
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
                        }else  if (index == 1){
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
                        }
                    }];
                    [sheet show];
                }
            }else{
                imageArr = _huanbaoImageArr;
            }
            break;
        case BaoJianShouXuCellTypeZhuJian:
            if (_canEdit) {
                if (indexPath.item == _zhujianImageArr.count) {
                    __weak typeof(self) weakSelf = self;
                    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"选择照片" buttonTitles:@[@"拍照",@"从手机相册选择"] redButtonIndex:-1 buttonClickedCallback: ^(NSInteger index) {
                        if (index == 0) {
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypeCamera];
                        }else  if (index == 1){
                            [weakSelf showImagePickerWithType:UIImagePickerControllerSourceTypePhotoLibrary];
                        }
                    }];
                    [sheet show];
                }
            }else{
                imageArr = _zhujianImageArr;
            }
            break;
    }
    if (imageArr.count != 0) {
        XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:imageArr currentImageIndex:indexPath.row];
        browser.pageControlStyle = XLPhotoBrowserPageControlStyleClassic;
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    _textViewText = textView.text;
    self.isContentReload = YES;
    switch (_type) {
        case BaoJianShouXuCellTypeFaGai:
            _fagaiTextViewText = _textViewText;
            break;
        case BaoJianShouXuCellTypeGuoTu:
            _guoTuTextViewText = _textViewText;
            break;
        case BaoJianShouXuCellTypeHuanBao:
            _huanBaoTextViewText = _textViewText;
            break;
        case BaoJianShouXuCellTypeZhuJian:
            _zhuJianTextViewText = _textViewText;
            break;
        case BaoJianShouXuCellTypeGuiHua:
            _guiHuaTextViewText = _textViewText;
            break;
    }
    [_superTableView reloadRowsAtIndexPaths:@[[_superTableView indexPathForCell:self]] withRowAnimation:(UITableViewRowAnimationNone)];
}

- (void)textView:(QMUITextView *)textView newHeightAfterTextChanged:(CGFloat)height{
    CGFloat newHeight = height + 177;
    _cellHeight = newHeight;
//    self.textViewText = textView.text;
}

- (CGFloat )returnCellHeight{
    if (_canEdit) {
        return _cellHeight;
    }else{
        return _cellHeight + [self returnContentTextHeightWithText:_textViewText withFont:_contentTextView.font];
    }
}

- (CGFloat )returnContentTextHeightWithText:(NSString *)content withFont:(UIFont *)font{
    QMUITextView *label = [[QMUITextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-25, NSIntegerMax)];
    label.text = content;
    label.font = font;
    [label sizeToFit];
    CGSize size = label.bounds.size;
    return size.height-25;
}

- (void)setCanEdit:(BOOL)canEdit{
    if (canEdit) {
        _contentTextView.editable = YES;
    }else{
        _contentTextView.editable = NO;
    }
    _canEdit = canEdit;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

#pragma mark 编辑照片
-(void)editViewWithImage:(UIImage *)image{
    [[self topViewController] hudWithText:@"图片上传中..."];
    [RequestManager uploadImageWithImage:image success:^(NSDictionary *obj) {
        [[self topViewController] removeHud];
        [[self topViewController].view makeToast:@"上传图片成功!"];
        NSDictionary *imageDic = obj[@"result"];
        NSString *imageUrl = imageDic[@"fileurl"];
        switch (self->_type) {
            case BaoJianShouXuCellTypeFaGai:
                [self->_fagaiImageArr addObject:imageUrl];
                break;
            case BaoJianShouXuCellTypeGuoTu:
                [self->_guotuImageArr addObject:imageUrl];
                break;
            case BaoJianShouXuCellTypeGuiHua:
                [self->_guihuaImageArr addObject:imageUrl];
                break;
            case BaoJianShouXuCellTypeHuanBao:
                [self->_huanbaoImageArr addObject:imageUrl];
                break;
            case BaoJianShouXuCellTypeZhuJian:
                [self->_zhujianImageArr addObject:imageUrl];
                break;
        }
        [self->_imagesCollectionView reloadData];
    } failure:^(NSString *error) {
        [[self topViewController] removeHud];
        [[self topViewController].view makeToast:@"上传图片失败,请重新选择上传!"];
    }];
}

#pragma mark UIImagePickerController - delegate
-(void)showImagePickerWithType:(UIImagePickerControllerSourceType )type{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = type;
    imagePickerController.delegate = self;
    [[self topViewController] presentViewController:imagePickerController animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self editViewWithImage:image];
    }];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}

- (void)setFagaiImageArr:(NSMutableArray *)fagaiImageArr{
    if (fagaiImageArr.count) {
        _fagaiImageArr = fagaiImageArr;
        [_imagesCollectionView reloadData];
    }else{
        _fagaiImageArr = [NSMutableArray array];
    }
}

- (void)setGuotuImageArr:(NSMutableArray *)guotuImageArr{
    if (guotuImageArr.count) {
        _guotuImageArr = guotuImageArr;
        [_imagesCollectionView reloadData];
    }else{
        _guotuImageArr = [NSMutableArray array];
    }
}

- (void)setGuihuaImageArr:(NSMutableArray *)guihuaImageArr{
    if (guihuaImageArr.count) {
        _guihuaImageArr = guihuaImageArr;
        [_imagesCollectionView reloadData];
    }else{
        _guihuaImageArr = [NSMutableArray array];
    }
}

- (void)setHuanbaoImageArr:(NSMutableArray *)huanbaoImageArr{
    if (huanbaoImageArr.count) {
        _huanbaoImageArr = huanbaoImageArr;
        [_imagesCollectionView reloadData];
    }else{
        _huanbaoImageArr = [NSMutableArray array];
    }
}

- (void)setZhujianImageArr:(NSMutableArray *)zhujianImageArr{
    if (zhujianImageArr.count) {
        _zhujianImageArr= zhujianImageArr;
        [_imagesCollectionView reloadData];
    }else{
        _zhujianImageArr = [NSMutableArray array];
    }
}

- (void)setType:(BaoJianShouXuCellType)type{
    _type = type;
    switch (type) {
        case BaoJianShouXuCellTypeFaGai:
            _contentTextView.text = _fagaiTextViewText;
            break;
        case BaoJianShouXuCellTypeHuanBao:
            _contentTextView.text = _huanBaoTextViewText;
            break;
        case BaoJianShouXuCellTypeZhuJian:
            _contentTextView.text = _zhuJianTextViewText;
            break;
        case BaoJianShouXuCellTypeGuiHua:
            _contentTextView.text = _guiHuaTextViewText;
            break;
        case BaoJianShouXuCellTypeGuoTu:
            _contentTextView.text = _guoTuTextViewText;
            break;
        default:
            break;
    }
}

@end
